﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AMS.DataAccess.Trademark.BO;
using AMS.DataAccess.Sys.Interfaces;
using AMS.DataAccess.Sys.BO;
using AMS.DataAccess.Trademark.Interfaces;
using AMS.DataAccess.Trademark.Filters;
using AMS.DataAccess.Trademark.BO.Enums;
using AMS.DataAccess.BO;

public partial class Cases_EditRegisterCase : BaseWorkPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!ParseParameters())
        {
            return;
        }

        if (!IsPostBack)
        {
            BindAttoneys();
            BindTasks();
            SetDefaultValues();

            ucCaseNav1.Visible = (action != "add");
            if(action == "edit")
            {
                BindCaseBasicInfo();
                drpTask.Enabled = false;
            }
        }
    }

    string action = "add";
    int caseId;

    bool ParseParameters()
    {
        action = Request.QueryString["op"];
        if (string.IsNullOrEmpty(action))
        {
            action = "add";
        }

        if (action == "edit")
        {
            if (!Utils.ParseIntQueryString(Request, "caseid", ref caseId))
            {
                GlobalTransfer.RedirectToErrorPageByParamMissing("caseid");
                return false;
            }
        }

        return true;
    }

    private void SetDefaultValues()
    {

    }

    #region Data binding
    private void BindAttoneys()
    {
        IUserManager userMgr = ManagerFactory.CreateUserManager();
        List<AMS.DataAccess.Sys.BO.UserInfo> attoneys = userMgr.GetTrademarkAttoneys(CallContext, false);
        if (attoneys == null)
        {
            attoneys = new List<AMS.DataAccess.Sys.BO.UserInfo>();
        }

        AMS.DataAccess.Sys.BO.UserInfo nullUser = new AMS.DataAccess.Sys.BO.UserInfo();
        nullUser.Name = Constants.PleaseSelectCaption;
        attoneys.Insert(0, nullUser);

        drpAttoney.DataSource = attoneys;
        drpAttoney.DataTextField = "DisplayName";
        drpAttoney.DataValueField = "AID";
        drpAttoney.DataBind();

        drpAttoney2.DataSource = attoneys;
        drpAttoney2.DataTextField = "DisplayName";
        drpAttoney2.DataValueField = "AID";
        drpAttoney2.DataBind();
    }

    void BindTasks()
    {
        ITaskManager taskMgr = ManagerFactory.CreateTaskManager();
        TaskFilter filter = new TaskFilter();
        // TODO: Enable owneer id filter
        // filter.OwnerID = CallContext.UserID;
        filter.StatusList.Add(TaskStatus.NewTask);
        filter.StatusList.Add(TaskStatus.UnCompleted);
        List<TaskInfo> tasks = taskMgr.GetNewCaseTasks(CallContext, filter);
        drpTask.DataSource = tasks;
        drpTask.DataTextField = "TaskName";
        drpTask.DataValueField = "AID";
        drpTask.DataBind();
        drpTask_SelectedIndexChanged(drpTask, EventArgs.Empty);
    }

    private void BindCaseCustomer(int taskId)
    {
        ITaskManager taskMgr = ManagerFactory.CreateTaskManager();
        CustomerInfo customer = taskMgr.GetTaskCustomer(CallContext, taskId);
        if (customer != null)
        {
            lblCustomerName.Text = customer.Name;
            hfCustomerID.Value = customer.AID.ToString();
        }
        else
        {
            // TODO: error process here
            MsgError("找不到对应的客户");
        }
    }

    void BindCaseBasicInfo()
    {
        ICaseBasicInfoManager caseMgr = ManagerFactory.CreateCaseBasicInfoManager();
        CaseDisplayInfo caseInfo = caseMgr.GetCaseBasicInfo(CallContext, caseId);
        if (caseInfo != null)
        {
            txtAttachedFileCount.Text = caseInfo.AttachFileCount.ToString();
            txtAuthDate.Text = Utils.DateTimeToString(caseInfo.AuthorizeDate);
            txtAuthLetterCount.Text = caseInfo.AuthorizeLetterCount.ToString();
            txtCustomerCaseCode.Text = caseInfo.CusCaseIndex;
            txtCustomerExptectedSubmitDate.Text = Utils.DateTimeToString(caseInfo.CusExpectSubmitDate);
            txtCustomerLawyer.Text = caseInfo.CusLawyer;
            txtCustomerWorkLawyer.Text = caseInfo.CusWorkLawyer;
            txtExpectedSubmitDate.Text = Utils.DateTimeToString(caseInfo.ExpectSubmitDate);
            txtName.Text = caseInfo.CaseName;
            txtNotes.Text = caseInfo.CaseNote;
            txtRecvInstructFileDate.Text = Utils.DateTimeToString(caseInfo.RecvInstructFileDateTime);
            txtSpecialNeeds.Text = caseInfo.SpecialNeeds;
            txtTotalAuthLetterNumber.Text = caseInfo.unionAuthorizeLetter;

            lblCaseIndex.Text = caseInfo.CaseIndex;
            lblCustomerName.Text = caseInfo.CustomerName;
            hfCustomerID.Value = caseInfo.CustomerID.ToString();
            Utils.SelectDropDownList(drpAttoney, caseInfo.Attorney.ToString());
            Utils.SelectDropDownList(drpAttoney2, caseInfo.Attorney2.ToString());

            lblTitle.Text = "编辑案件 - " + caseInfo.CaseIndex + " - " + caseInfo.CaseName + "(" + caseInfo.CustomerName + ")";
        }
        else
        {
            MsgError("找不到案件信息，可能已经被删除。");
        }
    }
    #endregion

    protected void btnSave_Click(object sender, EventArgs e)
    {
        RegisterCaseInfo caseInfo = RetriveCaseInfo();
        if (!ValidateCaseInfo(caseInfo))
        {
            return;
        }

        ICaseBasicInfoManager caseMgr = ManagerFactory.CreateCaseBasicInfoManager();
        if (action == "add")
        {
            caseMgr.AddCaseBasicInfo(CallContext, caseInfo);
            Server.Transfer("EditCaseApplicant.aspx?op=edit&caseid=" + caseInfo.AID.ToString());
        }
        else
        {
            caseInfo.AID = caseId;
            if (caseMgr.UpdateCaseBasicInfo(CallContext, caseInfo))
            {
                MsgInfo("已更新案件信息");
                Server.Transfer("EditCaseApplicant.aspx?op=edit&caseid=" + caseInfo.AID.ToString());
            }
            else
            {
                MsgError("更新失败，案件信息不存在。");
            }
        }
    }

    bool ValidateCaseInfo(RegisterCaseInfo caseInfo)
    {
        // TODO: add validation here
        return true;
    }

    private RegisterCaseInfo RetriveCaseInfo()
    {
        RegisterCaseInfo caseInfo = new RegisterCaseInfo();
        caseInfo.CaseType = TrademarkCaseType.Register;
        caseInfo.CaseStatus = TMCaseStatus.UnSubmitted;
        caseInfo.CusCaseIndex = txtCustomerCaseCode.Text;
        caseInfo.CusLawyer = txtCustomerLawyer.Text;
        caseInfo.CusWorkLawyer = txtCustomerWorkLawyer.Text;
        caseInfo.CaseName = txtName.Text;
        caseInfo.CaseNote = txtNotes.Text;
        caseInfo.SpecialNeeds = txtSpecialNeeds.Text;
        caseInfo.CustomerID = int.Parse(hfCustomerID.Value);
        caseInfo.unionAuthorizeLetter = txtTotalAuthLetterNumber.Text;
        IIndexProvider indexProvider = ManagerFactory.CreateIndexProvider();
        caseInfo.CaseIndex = indexProvider.NextTrademarkCaseIndex();

        if (!string.IsNullOrEmpty(txtAttachedFileCount.Text))
        {
            caseInfo.AttachFileCount = int.Parse(txtAttachedFileCount.Text);
        }

        if (!string.IsNullOrEmpty(txtAuthLetterCount.Text))
        {
            caseInfo.AuthorizeLetterCount = int.Parse(txtAuthLetterCount.Text);
        }

        // TODO: deal with attoney
        if (drpAttoney.SelectedIndex > 0)
        {
            caseInfo.Attorney = int.Parse(drpAttoney.SelectedValue);
            caseInfo.Attorney2 = int.Parse(drpAttoney2.SelectedValue);
        }
        if (!string.IsNullOrEmpty(txtAuthDate.Text))
        {
            caseInfo.AuthorizeDate = DateTime.Parse(txtAuthDate.Text);
        }

        if (!string.IsNullOrEmpty(txtCustomerExptectedSubmitDate.Text))
        {
            caseInfo.CusExpectSubmitDate = DateTime.Parse(txtCustomerExptectedSubmitDate.Text);
        }

        if (!string.IsNullOrEmpty(txtExpectedSubmitDate.Text))
        {
            caseInfo.ExpectSubmitDate = DateTime.Parse(txtExpectedSubmitDate.Text);
        }

        if (!string.IsNullOrEmpty(txtRecvInstructFileDate.Text))
        {
            caseInfo.RecvInstructFileDateTime=DateTime.Parse(txtRecvInstructFileDate.Text);
        }

        return caseInfo;
    }

    protected void drpTask_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (drpTask.Items.Count > 0)
        {
            string staskId = drpTask.SelectedValue;
            int taskId = Convert.ToInt32(staskId);
            BindCaseCustomer(taskId);
        }
    }

}
